package com.lzq.leetcode.hoot100;

import java.util.ArrayList;
import java.util.List;

public class s54 {

    public List<Integer> spiralOrder(int[][] matrix) {

        List<Integer> ans = new ArrayList<>();
        int l = 0, r = matrix[0].length - 1;
        int u = 0, d = matrix.length - 1;

        while (true) {
            for (int i=l; i<=r; i++) ans.add(matrix[u][i]);
            if (++u > d)    break;

            for (int i=u; i<=d; i++) ans.add(matrix[i][r]);
            if (++r < l)   break;

            for (int i=r; i>=l; i--) ans.add(matrix[d][i]);
            if (--d < u)   break;

            for (int i=d; i>=u; i--) ans.add(matrix[i][l]);
            if (++l > r)   break;
        }
        return ans;
    }

    public static void main(String[] args) {
        System.out.println(new s54().spiralOrder(new int[][]{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}));
    }
}
